import { useEffect, useRef, useState } from 'react'
import './index.scss'
import Hls from 'hls.js'
import plyr from 'plyr'
import 'plyr/dist/plyr.css'
// import { useWindowDimensions } from '@/hook'
import { IconContext } from 'react-icons'
import { HiOutlineSwitchHorizontal } from 'react-icons/hi'
// import { useOpenMessageThrottle } from '@/hook'
import { useNavigate, useParams } from 'react-router-dom'
import BulletScreen, { StyledBullet } from 'rc-bullets-ts'

const headUrl =
  'https://dullwolf.oss-cn-shenzhen.aliyuncs.com/1143644962798174208.png'

const VideoPlayer = ({
  source,
  internalPlayer,
  setInternalPlayer,
  banner,
  title,
  totalEpisodes,
  currentEpisode,
  type,
}) => {
  // const { width } = useWindowDimensions()
  // const openMessage = useOpenMessageThrottle(1000)

  // 弹幕屏幕
  const screenElRef = useRef(null)
  const screenRef = useRef(null)
  // 弹幕内容
  const [bullet, setBullet] = useState('')

  const navigate = useNavigate()
  const id = useParams().id
  const ep = useParams().ep

  let src = source

  useEffect(() => {
    const video = document.getElementById('player')
    let flag = true
    const defaultOptions = {
      captions: { active: true, update: true, language: 'auto' },
      controls:
        [
              'play-large',
              'rewind',
              'play',
              'fast-forward',
              'progress',
              'current-time',
              'duration',
              'fullscreen',
        ],
    }

    // 给页面中某个元素初始化弹幕屏幕，一般为一个大区块。此处的配置项全局生效
    screenRef.current = new BulletScreen(screenElRef.current, { duration: 20 })

    if (type === 'mp4') {
      const player = new plyr(video, defaultOptions)
      player.source = {
        type: 'video',
        poster: banner,
        sources: [
          {
            src: src,
            type: 'video/mp4',
          },
        ],
      }
    }

    if (Hls.isSupported()) {
      const hls = new Hls()
      hls.loadSource(src)
      hls.attachMedia(video)

      hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
        let player = new plyr(video, defaultOptions)
        let plyer

        player.on('ready', () => {
          plyer = document.querySelector('.plyr__controls')
          document
            .querySelector('.plyr__video-wrapper')
            .addEventListener('click', () => {
              let regexp = /android|iphone|kindle|ipad/i
              if (
                regexp.test(navigator.userAgent) &&
                getComputedStyle(player.elements.controls).opacity === '1'
              ) {
                player.togglePlay()
              }
            })

          var tapedTwice = false
          function tapHandler(event) {
            if (!tapedTwice) {
              tapedTwice = true
              setTimeout(function () {
                tapedTwice = false
              }, 300)
              return false
            }
            event.preventDefault()
            player.fullscreen.toggle()
          }
          document
            .querySelector('.plyr__video-wrapper')
            .addEventListener('touchstart', tapHandler)
        })

        player.on('enterfullscreen', (event) => {
          plyer.appendChild(button)
          window.screen.orientation.lock('landscape')
        })

        player.on('exitfullscreen', (event) => {
          document.querySelector('.skip-button').remove()
          window.screen.orientation.lock('portrait')
        })

        player.on('timeupdate', function (e) {
          var time = player.currentTime,
            lastTime = localStorage.getItem(title)
          if (time > lastTime) {
            localStorage.setItem(title, Math.round(player.currentTime))
          }
        })

        player.on('ended', function () {
          localStorage.removeItem(title)
          console.log(currentEpisode + ' _ ' + totalEpisodes)
          console.log(ep + ' _ ' + id)

          if (
            localStorage.getItem('autoplay') === 'true' &&
            parseInt(currentEpisode) !== parseInt(totalEpisodes)
          ) {
            navigate(`/anime/play/${id}/${ep + 1}`)
          }
        })

        player.on('play', function (e) {
          if (flag) {
            var lastTime = localStorage.getItem(title)
            if (lastTime !== null && lastTime > player.currentTime) {
              player.forward(parseInt(lastTime))
            }
            flag = false
          }
        })

        player.on('seeking', (event) => {
          localStorage.setItem(title, Math.round(player.currentTime))
        })
      })
      hls.attachMedia(video)
      window.hls = hls
    }
  }, [])

  // 弹幕内容输入事件处理
  const handleChange = ({ target: { value } }) => {
    setBullet(value)
  }

  // 发送弹幕
  const handleSend = () => {
    if (bullet && screenRef.current) {
      screenRef.current.push(
        <StyledBullet head={headUrl} msg={bullet} backgroundColor={'#fff'} />
      )
    }
  }

  return (
    <div
      style={{
        marginBottom: '1rem',
      }}
    >
      <div className="video-header">
        <IconContext.Provider
          value={{
            size: '0.8rem',
            style: { verticalAlign: 'middle' },
          }}
        >
          {!internalPlayer && (
            <span>
              内部播放器 {'('}
              {title}
              {')'}
            </span>
          )}
          <div className="danmu-input">
            <input className='comment-input' value={bullet} onChange={handleChange} />
            <button onClick={handleSend}>发送</button>
          </div>
          <div className="tooltip">
            <button
              title="切换外部播放器"
              onClick={() => {
                openMessage({
                  type: 'success',
                  content: '切换外部播放器',
                })
                setInternalPlayer(!internalPlayer)
              }}
            >
              <HiOutlineSwitchHorizontal />
            </button>
          </div>
        </IconContext.Provider>
      </div>
      <div className="video-container">
        <video
          id="player"
          data-poster={banner}
          playsInline
          style={{ aspectRatio: 16 / 9 }}
        />
        <div className='screen' ref={screenElRef}></div>
      </div>
    </div>
  )
}

export default VideoPlayer
